// Copyright © 2022 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package clam

import (
	"context"
	_ "embed"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"slices"
	"strings"
	"text/template"

	"github.com/openclarity/openclarity/core/log"
	"github.com/openclarity/openclarity/scanner/common"
	"github.com/openclarity/openclarity/scanner/families"
	"github.com/openclarity/openclarity/scanner/families/malware/clam/config"
	"github.com/openclarity/openclarity/scanner/families/malware/clam/constants"
	"github.com/openclarity/openclarity/scanner/families/malware/types"
	familiesutils "github.com/openclarity/openclarity/scanner/families/utils"
	"github.com/openclarity/openclarity/scanner/utils"
)

const ScannerName = "clam"

//go:embed templates/clamd.conf
var clamdConfigTemplate string

type Scanner struct {
	config config.Config
}

func New(ctx context.Context, _ string, config types.ScannersConfig) (families.Scanner[*types.ScannerResult], error) {
	scanner := &Scanner{
		config: config.Clam,
	}

	// Prepare freshclam to sync database data
	if err := scanner.prepareFreshclam(ctx); err != nil {
		return nil, fmt.Errorf("failed to run freshclam: %w", err)
	}

	// Prepare clam daemon
	if err := scanner.prepareClamDaemon(ctx); err != nil {
		return nil, fmt.Errorf("failed to run freshclam: %w", err)
	}

	return scanner, nil
}

// nolint: cyclop
func (s *Scanner) Scan(ctx context.Context, inputType common.InputType, userInput string) (*types.ScannerResult, error) {
	if !inputType.IsOneOf(common.ROOTFS, common.DIR, common.IMAGE, common.DOCKERARCHIVE, common.OCIARCHIVE, common.OCIDIR) {
		return nil, fmt.Errorf("unsupported input type=%v", inputType)
	}

	// Prepare input that needs to be scanned
	fsScanPath, cleanup, err := familiesutils.ConvertInputToFilesystem(ctx, inputType, userInput)
	if err != nil {
		return nil, fmt.Errorf("failed to convert input to filesystem: %w", err)
	}
	defer cleanup()

	// Scan path using clamscan or clamdscan
	var scanOutput []byte
	var scanTool string
	if s.config.UseNativeClamscan {
		scanTool = "clamscan"
		scanOutput, err = s.runClamScan(ctx, fsScanPath)
	} else {
		scanTool = "clamdscan"
		scanOutput, err = s.runClamScanWithDaemon(ctx, fsScanPath)
	}
	if err != nil {
		return nil, fmt.Errorf("failed to run %s: %w", scanTool, err)
	}

	detectedMalware, summary := parseMalwareScanOutput(string(scanOutput))

	return &types.ScannerResult{
		Source:   userInput,
		Malwares: detectedMalware,
		Summary:  summary,
	}, nil
}

func (s *Scanner) runClamScan(ctx context.Context, fsScanPath string) ([]byte, error) {
	logger := log.GetLoggerFromContextOrDefault(ctx)

	clamScanPath, err := exec.LookPath(s.config.GetClamScanBinaryPath())
	if err != nil {
		return nil, fmt.Errorf("failed to lookup executable %s: %w", s.config.ClamScanBinaryPath, err)
	}
	logger.Debugf("found clamscan binary at: %s", clamScanPath)

	// Define default clamscan args to run
	args := []string{
		"--infected",
		"--recursive",
	}

	// --exclude=REGEX, --exclude-dir=REGEX
	// Don't scan file/directory names matching regular expression. These options can be used multiple times.
	for _, file := range s.config.ClamScanExcludeFiles {
		args = append(args, fmt.Sprintf("--exclude=%q", file))
	}

	for _, dir := range s.config.ClamScanExcludeDirs {
		args = append(args, fmt.Sprintf("--exclude-dir=%q", dir))
	}

	// Append files/directories to scan as a last argument - clamscan [options] [file/directory/-]
	args = append(args, fsScanPath)

	// Execute the clamscan command
	logger.Infof("Running clamscan for %s...", fsScanPath)

	// nolint:gosec
	clamScanCommand := exec.CommandContext(ctx, clamScanPath, args...)
	out, err := utils.RunCommand(clamScanCommand)
	if err != nil {
		/* If the error is that malware was found, this is not an actual error, Clam returns
		   a non 0 exit code when malware was found */
		var runError utils.CmdRunError
		if !errors.As(err, &runError) || !strings.Contains(string(runError.Stdout), constants.ScanSummaryText) {
			return nil, fmt.Errorf("failed to run clam command: %w", err)
		}

		out = runError.Stdout
	}

	return out, nil
}

func (s *Scanner) runClamScanWithDaemon(ctx context.Context, fsScanPath string) ([]byte, error) {
	logger := log.GetLoggerFromContextOrDefault(ctx)

	clamDaemonClientPath, err := exec.LookPath(s.config.GetClamDaemonClientBinaryPath())
	if err != nil {
		return nil, fmt.Errorf("failed to lookup executable %s: %w", s.config.ClamDaemonClientBinaryPath, err)
	}
	logger.Debugf("found clamdscan binary at: %s", clamDaemonClientPath)

	// Define default clamdscan args to run
	args := []string{
		"--multiscan",
		"--stream",
		"--infected",
	}

	// Append custom config if provided
	if s.config.ClamDaemonConfigPath != "" {
		args = append(args, "--config-file", s.config.ClamDaemonConfigPath)
	}

	// Append files/directories to scan as a last argument - clamdscan [options] [file/directory/-]
	args = append(args, fsScanPath)

	// Execute the clamdscan command
	logger.Infof("Running clamdscan for %s...", fsScanPath)

	// nolint:gosec
	clamdScanCommand := exec.CommandContext(ctx, clamDaemonClientPath, args...)
	out, err := utils.RunCommand(clamdScanCommand)
	if err != nil {
		/* If the error is that malware was found, this is not an actual error, Clamd returns
		   a non 0 exit code when malware was found */
		var runError utils.CmdRunError
		if !errors.As(err, &runError) || !strings.Contains(string(runError.Stdout), constants.ScanSummaryText) {
			return nil, fmt.Errorf("failed to run clamdscan command: %w", err)
		}

		out = runError.Stdout
	}

	return out, nil
}

func (s *Scanner) prepareClamDaemon(ctx context.Context) error {
	// Check if daemon mode was requested
	if s.config.UseNativeClamscan {
		return nil
	}

	logger := log.GetLoggerFromContextOrDefault(ctx)

	clamDaemonPath, err := exec.LookPath(s.config.GetClamDaemonBinaryPath())
	if err != nil {
		return fmt.Errorf("failed to lookup executable %s: %w", s.config.ClamDaemonBinaryPath, err)
	}
	logger.Debugf("found clamd binary at: %s", clamDaemonPath)

	// Define default clamd args to run
	var args []string

	// Use default clamd configuration if it is not provided
	if s.config.ClamDaemonConfigPath == "" {
		s.config.ClamDaemonConfigPath = filepath.Join(os.TempDir(), "clamd.conf")
		err = s.createDefaultClamdConfig()
		if err != nil {
			return fmt.Errorf("unable to create default clamd configuration: %w", err)
		}
	}
	args = append(args, "--config-file", s.config.ClamDaemonConfigPath)

	// Execute clamd command
	logger.Infof("Starting clam daemon process...")

	// nolint:gosec
	clamDaemonCommand := exec.CommandContext(ctx, clamDaemonPath, args...)
	_, err = utils.RunCommand(clamDaemonCommand)
	if err != nil {
		// If the error is that daemon is already running, this is not an actual error
		var runError utils.CmdRunError
		if !errors.As(err, &runError) || !strings.Contains(runError.Stderr, constants.ClamDaemonAlreadyRunning) {
			return fmt.Errorf("failed to run clamd command: %w", err)
		}
	}

	logger.Info("Started clam daemon process")

	return nil
}

func (s *Scanner) prepareFreshclam(ctx context.Context) error {
	logger := log.GetLoggerFromContextOrDefault(ctx)

	freshClamPath, err := exec.LookPath(s.config.GetFreshclamBinaryPath())
	if err != nil {
		return fmt.Errorf("failed to lookup executable %s: %w", s.config.FreshclamBinaryPath, err)
	}
	logger.Debugf("found freshclam binary at: %s", freshClamPath)

	// Sync freshclam configuration
	logger.Infof("Syncing freshclam configuration...")

	if err := s.syncFreshclamConfig(); err != nil {
		return fmt.Errorf("failed to sync freshclam config: %w", err)
	}

	// Define default freshclam args to run
	args := []string{
		"--config-file", s.config.GetFreshclamConfigPath(),
	}

	// Execute freshclam command
	logger.Infof("Running freshclam...")

	// nolint:gosec
	freshclamCommand := exec.CommandContext(ctx, freshClamPath, args...)
	freshclamOut, err := utils.RunCommand(freshclamCommand)
	if err != nil {
		return fmt.Errorf("failed to run freshclam command: %w", err)
	}

	logger.Infof("freshclam finished with success: %s", string(freshclamOut))

	return nil
}

func (s *Scanner) syncFreshclamConfig() error {
	var configContents []byte
	var configLines []string

	// Attempt to read freshclam.conf file
	_, err := os.Stat(s.config.GetFreshclamConfigPath())
	if os.IsNotExist(err) {
		return fmt.Errorf("freshclam.conf not found at %s", s.config.GetFreshclamConfigPath())
	} else if err != nil {
		return fmt.Errorf("failed to check freshclam.conf: %w", err)
	}

	configContents, err = os.ReadFile(s.config.GetFreshclamConfigPath())
	if err != nil {
		return fmt.Errorf("failed to read freshclam.conf: %w", err)
	}

	// Handle alternative freshclam mirror URL
	if s.config.AlternativeFreshclamMirrorURL != "" {
		configLines = strings.Split(string(configContents), "\n")

		// Comment out any existing conflicting options
		for i, line := range configLines {
			if strings.HasPrefix(line, constants.PrivateMirrorConf) || strings.HasPrefix(line, constants.ScriptedUpdatesConf) {
				configLines[i] = "# " + line
			}
		}

		// Add our mirror options
		mirrorLine := fmt.Sprintf("%s %s", constants.PrivateMirrorConf, s.config.AlternativeFreshclamMirrorURL)
		scriptedUpdatesLine := constants.ScriptedUpdatesConf + " no"

		configLines = append(configLines, mirrorLine, scriptedUpdatesLine)

		// Re-render the file
		configContents = []byte(strings.Join(configLines, "\n"))

		writePermissions := 0o600
		err = os.WriteFile(s.config.GetFreshclamConfigPath(), configContents, os.FileMode(writePermissions))
		if err != nil {
			return fmt.Errorf("failed to write freshclam.conf: %w", err)
		}
	}

	return nil
}

func (s *Scanner) createDefaultClamdConfig() error {
	t := template.New("clamd.conf")
	t, err := t.Parse(clamdConfigTemplate)
	if err != nil {
		return fmt.Errorf("unable to parse template: %w", err)
	}

	f, err := os.Create(s.config.ClamDaemonConfigPath)
	if err != nil {
		return fmt.Errorf("unable to create file: %w", err)
	}
	defer f.Close()

	err = t.Execute(f, struct {
		LocalSocket   string
		ExcludedPaths []string
	}{
		filepath.Join(os.TempDir(), "clamd.sock"),
		slices.Concat(s.config.ClamScanExcludeDirs, s.config.ClamScanExcludeFiles),
	})
	if err != nil {
		return fmt.Errorf("unable te render config file template: %w", err)
	}

	return nil
}
